<?php
/**
 * Created by PhpStorm.
 * User: MACHENIKE
 * Date: 2017/7/14
 * Time: 11:26
 */

namespace Org\Payment;

abstract class pay_message implements base {

    protected $message = [];

    function __construct()
    {
        $sign['channelNo']  = 'F003';
        $sign['optType']    = '';
        $sign['lang']       = 'zh_CN';
        $sign['timestamp']  = $this->getMillisecond();
        $sign['randStr']    = md5(uniqid());
        $sign['publicKeyNo']= '0000';
//        $sign.class['data']       = urlencode(base64_encode(json_encode('test'))); FT_P116
        $sign['data']       = '';
        $sign['version']    = '1.0';
        $sign['sign']       = '';

        $this->message = $sign;
    }

    /**
     * 获取报文信息 用于对接验签接口
     * @return array
     */
    public function getMessage()
    {
        // TODO: Implement getMessage() method.
        $this->setData();//设置data请求
        $this->setOptType();//设置optType类型
        $this->setSign();//组装并设置sign
        return $this->message;
    }

    /**
     * 设置请求内容
     * @param array $data 请求内容
     */
    public function setData()
    {
        // TODO: Implement setData() method.
        $this->message['data'] = urlencode(base64_encode(json_encode($this->set_data(),JSON_UNESCAPED_UNICODE+JSON_UNESCAPED_SLASHES)));
    }

    /**
     * @param string $optType 请求编码
     */
    public function setOptType()
    {
        // TODO: Implement setOptType() method.
        $this->message['optType'] = $this->set_optType();
    }


    /**
     * 设置unix时间戳
     * @return string
     */
    private function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return $t2 . ceil( ($t1 * 1000) );
    }

    /**
     * 获取rsa签名后的数据
     * @return string
     */
    private function setSign() {
        //组装数据
        $sign['channelNo']      = $this->message['channelNo'];
        $sign['lang']           = $this->message['lang'];
        $sign['timestamp']      = $this->message['timestamp'];
        $sign['randStr']        = $this->message['randStr'];
        $sign['publicKeyNo']    = $this->message['publicKeyNo'];
        $sign['optType']        = $this->message['optType'];
        $sign['data']           = $this->message['data'];
        $sign['version']        = $this->message['version'];

        $_sign = $this->assemble_message($sign);
        $this->message['sign'] = bin2hex(rsaSign($_sign, __ROOT__ . 'rsa_private_key.pem'));
    }

    /**
     * 组装数据并按规律进行处理
     * @param array $message 待处理数据
     * @return string sha1并进行小写压缩后的数据
     */
    private function assemble_message(array $message)
    {
        ksort($message);
        $str = http_build_query($message);
        $str = urldecode($str);
        $str = sha1($str);
        $_sign = strtolower($str);
        return $_sign;
    }

    //设置data内容
    abstract function set_data();

    //设置optType内容
    abstract function set_optType();
}